package com.wjk.kylin.mall.auth.config;

import cn.hutool.core.util.StrUtil;
import com.wjk.kylin.mall.auth.security.core.clientdetails.ClientDetailsServiceImpl;
import com.wjk.kylin.mall.auth.security.core.userdetails.member.MemberUserDetails;
import com.wjk.kylin.mall.auth.security.core.userdetails.member.MemberUserDetailsServiceImpl;
import com.wjk.kylin.mall.auth.security.core.userdetails.user.AdminUserDetails;
import com.wjk.kylin.mall.auth.security.core.userdetails.user.AdminUserDetailsServiceImpl;
import com.wjk.kylin.mall.auth.security.extension.captcha.CaptchaTokenGranter;
import com.wjk.kylin.mall.auth.security.extension.refresh.PreAuthenticatedUserDetailsServiceImpl;
import com.wjk.kylin.mall.common.core.constant.Constants;
import com.wjk.kylin.mall.common.redis.utils.RedisUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import java.security.KeyPair;
import java.util.*;

/**
 * @Author: wangjinkui
 * @Date: 2021/6/2
 * @Description : 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
//    @Autowired
//    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    private MemberUserDetailsServiceImpl memberUserDetailsService;
    @Autowired
    private AdminUserDetailsServiceImpl adminUserDetailsService;
    @Autowired
    private ClientDetailsServiceImpl clientDetailsService;
//    @Autowired
//    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisUtil redisUtil;

//    /**
//     * 配置客户端详情(数据库)
//     */
//    @Override
//    @SneakyThrows
//    public void configure(ClientDetailsServiceConfigurer clients) {
//        /*
//        * String CLIENT_DETAILS_FIELDS = "client_id, CONCAT('{noop}',client_secret) as client_secret, resource_ids, scope, "
//            + "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
//            + "refresh_token_validity, additional_information, autoapprove";
//        * String BASE_CLIENT_DETAILS_SQL = "select " + CLIENT_DETAILS_FIELDS + " from oauth_client_details";
//        * String FIND_CLIENT_DETAILS_SQL = BASE_CLIENT_DETAILS_SQL + " order by client_id";
//        * String SELECT_CLIENT_DETAILS_SQL = BASE_CLIENT_DETAILS_SQL + " where client_id = ?";
//        * */
//        JdbcClientDetailsServiceImpl jdbcClientDetailsService = new JdbcClientDetailsServiceImpl(dataSource);
//        jdbcClientDetailsService.setFindClientDetailsSql(AuthConstants.FIND_CLIENT_DETAILS_SQL);
//        jdbcClientDetailsService.setSelectClientDetailsSql(AuthConstants.SELECT_CLIENT_DETAILS_SQL);
//        clients.withClientDetails(jdbcClientDetailsService);
//    }

    /**
     * 客户端信息配置
     */
    @Override
    @SneakyThrows
    public void configure(ClientDetailsServiceConfigurer clients) {
        // 此处客户端可以写死到内存中,也可以从数据库读取,视具体业务而变,客户端作用此处不在讲述
        clients.withClientDetails(clientDetailsService);
//        clients.inMemory()
//                .withClient(Constants.ADMIN_CLIENT_ID)//后台管理client_id
//                .secret(passwordEncoder.encode("123456"))// 客户端密码
//                .autoApprove(true)// 自动授权配置
//                .scopes("all")
//                // 客户端授权类型(authorization_code:授权码类型 password:密码类型 implicit:简化类型/隐式类型 client_credentials:客户端类型 refresh_token:该为特例，加了才可以刷新授权)
//                .authorizedGrantTypes("password","captcha","refresh_token")
//                .accessTokenValiditySeconds(3600 * 24)
//                .refreshTokenValiditySeconds(3600 * 24 * 7)
//                .and()
//                .withClient(Constants.PORTAL_CLIENT_ID)//前台商城client_id
//                .secret(passwordEncoder.encode("123456"))
//                .scopes("all")
//                .authorizedGrantTypes("password", "refresh_token")
//                .accessTokenValiditySeconds(3600*24)
//                .refreshTokenValiditySeconds(3600*24*7);
    }

    /**
     * 配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        // 增强jwt载荷的内容
        tokenEnhancers.add(tokenEnhancer());
        // 添加jwt的加密公钥
        tokenEnhancers.add(jwtAccessTokenConverter());
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);

        // 获取原有默认授权模式(授权码模式、密码模式、客户端模式、简化模式)的授权者
        List<TokenGranter> granterList = new ArrayList<>(Collections.singleton(endpoints.getTokenGranter()));
        // 添加验证码授权模式授权者
        granterList.add(new CaptchaTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
                endpoints.getOAuth2RequestFactory(), authenticationManager, redisUtil
        ));
//        // 添加手机短信验证码授权模式的授权者
//        granterList.add(new SmsCodeTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
//                endpoints.getOAuth2RequestFactory(), authenticationManager
//        ));
//        // 添加微信授权模式的授权者
//        granterList.add(new WechatTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
//                endpoints.getOAuth2RequestFactory(), authenticationManager
//        ));
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(granterList);


        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter())
                .tokenEnhancer(tokenEnhancerChain)
                .tokenGranter(compositeTokenGranter)
                // 使用自己实现的用户密码校验逻辑
//                .userDetailsService(userDetailsService)
                // refresh_token有两种使用方式：重复使用(true)、非重复使用(false)，默认为true
                //      1.重复使用：access_token过期刷新时， refresh token过期时间未改变，仍以初次生成的时间为准
                //      2.非重复使用：access_token过期刷新时， refresh_token过期时间延续，在refresh_token有效期内刷新而无需失效再次登录
//                .reuseRefreshTokens(false)
                .tokenServices(tokenServices(endpoints));
    }

    public DefaultTokenServices tokenServices(AuthorizationServerEndpointsConfigurer endpoints) {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        tokenEnhancers.add(tokenEnhancer());
        tokenEnhancers.add(jwtAccessTokenConverter());
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);

        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(endpoints.getTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setTokenEnhancer(tokenEnhancerChain);

        // 多用户体系下，刷新token再次认证客户端ID和 UserDetailService 的映射Map
        Map<String, UserDetailsService> clientUserDetailsServiceMap = new HashMap<>();
        clientUserDetailsServiceMap.put(Constants.ADMIN_CLIENT_ID, adminUserDetailsService); // 系统管理客户端
        clientUserDetailsServiceMap.put(Constants.PORTAL_CLIENT_ID, memberUserDetailsService); // Android、IOS、H5 移动客户端
        clientUserDetailsServiceMap.put(Constants.WEB_CLIENT_ID, memberUserDetailsService); // 微信小程序客户端

        // 刷新token模式下，重写预认证提供者替换其AuthenticationManager，可自定义根据客户端ID和认证方式区分用户体系获取认证用户信息
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new PreAuthenticatedUserDetailsServiceImpl<>(clientUserDetailsServiceMap));
        tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));

        // refresh_token有两种使用方式：重复使用(true)、非重复使用(false)，默认为true
        //      1.重复使用：access_token过期刷新时， refresh token过期时间未改变，仍以初次生成的时间为准
        //      2.非重复使用：access_token过期刷新时， refresh_token过期时间延续，在refresh_token有效期内刷新而无需失效再次登录
        tokenServices.setReuseRefreshToken(true);

        return tokenServices;
    }



    /**
     * 允许表单认证
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.allowFormAuthenticationForClients();
    }

//    /**
//     * 自定义认证异常响应数据
//     */
//    @Bean
//    public AuthenticationEntryPoint authenticationEntryPoint() {
//        return (request, response, e) -> {
//            response.setStatus(HttpStatus.HTTP_OK);
//            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            response.setHeader("Cache-Control", "no-cache");
//            response.getWriter().print(JSONObject.toJSONString(BaseOutDTO.error(BaseError.CLIENT_AUTHENTICATION_FAILED)));
//            response.getWriter().flush();
//        };
//    }
//
//    @Bean
//    public DaoAuthenticationProvider authenticationProvider() {
//        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
//        provider.setHideUserNotFoundExceptions(false); // 用户不存在异常抛出
//        provider.setUserDetailsService(userDetailsService);
//        provider.setPasswordEncoder(passwordEncoder);
//        return provider;
//    }

    /**
     * 使用非对称加密算法对token签名
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair());
        return converter;
    }

    /**
     * 从classpath下的密钥库中获取密钥对(公钥+私钥)
     */
    @Bean
    public KeyPair keyPair() {
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("mall-jwt.jks"), "123qwe".toCharArray());
        return factory.getKeyPair("mall-jwt", "123qwe".toCharArray());
    }

    /**
     * JWT内容增强
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            Map<String, Object> map = new HashMap<>(2);
//            CustomUserDetails user = (CustomUserDetails) authentication.getUserAuthentication().getPrincipal();
//            map.put(Constants.USER_ID_KEY, user.getId());
//            map.put(Constants.NICK_NAME_KEY, user.getNickname());

            Object principal = authentication.getUserAuthentication().getPrincipal();
            if (principal instanceof AdminUserDetails) {
                AdminUserDetails sysUserDetails = (AdminUserDetails) principal;
                map.put(Constants.USER_ID_KEY, sysUserDetails.getUserId());
                map.put(Constants.NICK_NAME_KEY, sysUserDetails.getUsername());
                if (StrUtil.isNotBlank(sysUserDetails.getAuthenticationMethod())) {
                    map.put("authenticationMethod", sysUserDetails.getAuthenticationMethod());
                }
            } else if (principal instanceof MemberUserDetails) {
                MemberUserDetails memberUserDetails = (MemberUserDetails) principal;
                map.put(Constants.USER_ID_KEY, memberUserDetails.getUserId());
                map.put(Constants.NICK_NAME_KEY, memberUserDetails.getUsername());
                if (StrUtil.isNotBlank(memberUserDetails.getAuthenticationMethod())) {
                    map.put("authenticationMethod", memberUserDetails.getAuthenticationMethod());
                }
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
            return accessToken;
        };
    }

}
